# coding=utf-8


from random import randrange
import pygame
#初始化游戏


pygame.init()
#创建游戏窗口


width,height=640,480
screen=pygame.display.set_mode((width,height))
# 蛇身


snake = [pygame.Rect(10, 10, 10, 10), pygame.Rect(10, 20, 10, 10)]

# 位移坐标


up = (0, -10)
down = (0, 10)
left = (-10, 0)
right = (10, 0)

# 蛇移动的方向


dir = down

# 时钟


clock = pygame.time.Clock()
# 食物


food = None
# 分数


score = 0
#字体


font = pygame.font.SysFont('simhei', 20)
#死亡


dead = False

while True:

    # 时钟延时


    clock.tick(6)

    # 获取pygame事件


    event = pygame.event.poll()
    # 判断pygame事件类型为游戏退出


    if event.type == pygame.QUIT:
        pygame.quit()
    # 判断pygame事件类型为键盘按下


    if event.type == pygame.KEYDOWN:
        # 上键按下


        if event.key == pygame.K_UP and dir != down:
            # 改变蛇头方向


            dir = up
        # 下键按下


        if event.key == pygame.K_DOWN and dir != up:
            dir = down
        # 左键按下


        if event.key == pygame.K_LEFT and dir != right:
            dir = left
        # 右键按下


        if event.key == pygame.K_RIGHT and dir != left:
            dir = right

    screen.fill((255, 255, 255))

    # 死亡


    if dead:
    	screen.fill((0, 0, 0))
    	surface = font.render(u"Game Over 分数:" + str(score), True, (255,255,255))
    	screen.blit(surface, (200, 0))
    	pygame.display.flip()
    	continue

    # 绘画食物


    if food is None:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)
    pygame.draw.rect(screen, (0, 0, 0), food)

    # 遍历保存蛇身的列表，绘画出蛇


    for rect in snake:
        pygame.draw.rect(screen, (randrange(255), randrange(255), randrange(255)), rect)
    # 取列表最后一个元素，偏移到dir，得到一个矩形坐标对象，也就是蛇要移动的下一个坐标


    node = snake[-1].move(dir)


    # 判断死亡


    if node in snake or node.left > width or node.top > height or node.left < 0 or node.top < 0:
    	dead = True
    	continue

    if node == food:
        food = None
        score += 10
    else:
        del snake[0]


    # 将得到的坐标放到蛇列表里面，这样下次循环就会移动


    snake.append(node)

    # 分数


    surface = font.render(u'分数'+str(score), True, (0,0,0))
    screen.blit(surface, (560, 0))

    # 更新界面


    pygame.display.flip()
